package cn.easyutil.project.web.handler;

import cn.easyutil.project.base.context.Context;
import cn.easyutil.util.javaUtil.JsonUtil;
import cn.easyutil.util.javaUtil.LoggerUtil;
import cn.easyutil.util.javaUtil.StringUtil;
import cn.easyutil.project.web.advice.RequestBeforeAdvice;
import cn.easyutil.project.web.util.RequestPool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

public class DefaultRequestBeforeAdvice implements RequestBeforeAdvice {
    @Override
    public boolean process(HttpServletRequest request, HttpServletResponse response, Method controllerMethod, Class<?> controllerClass) {
        String requestUri = request.getRequestURI();
        if(!requestUri.startsWith("/")){
            requestUri = "/"+requestUri;
        }
        if(controllerClass == null){
            controllerClass = this.getClass();
        }
        //打印日志
        logger(requestUri,request.getParameterMap(),controllerClass);
        return checkUri(requestUri);

    }

    protected void logger(String requestUri,Map<String, String[]> parameterMap,Class<?> controllerClass){
        if(parameterMap!=null && !parameterMap.isEmpty()){
            LoggerUtil.info(controllerClass,"接口【"+requestUri+"】的请求参数为:"+ JsonUtil.beanToJson(parameterMap));
        }
    }

    protected boolean checkUri(String requestUri){
        RequestPool.setCacheAttribute(Context.threadLocal_request_url, requestUri);
        RequestPool.useResponse.set(false);
        if(requestUri.contains("/null/")) {
            LoggerUtil.info(this.getClass(),"拦截null请求，中断");
            return false;
        }
        if (requestUri.startsWith(RequestPool.URI_PREFIX)) {
            RequestPool.useResponse.set(true);
        }
        return true;
    }
}
